<template>
	<div>
		<van-nav-bar title="订单详情" left-arrow @click-left="$utils.back($route.path)" />
		<div class="nav-top">
			<div class="title"><span class="status">{{ model.StateName }}</span><span v-if="model.State === 0 && showPayTime">请在{{
				remainder }}内完成支付</span></div>
			<!-- 订单顶部 -->
			<orderTop :info="model" :isArtificer="isArtificer"></orderTop>
			<div class="pb-220">
				<!-- 订单内容 -->
				<div class="bg-white mg-24 pd-24 br-16">
					<div class="flex flex-s-c ">
						<div class="fs-28 fw-b">服务项目</div>
						<div class="flex endtitle" v-if="model.State === 3 && showServiceTime">
							<div class="color-gray7 mr-18">距离结束</div>
							<div class="endtime">{{ h }}</div>:<div class="endtime">{{ m }}</div>:<div class="endtime">{{ s }}</div>
						</div>
					</div>
					<div v-if="model.DetailList && model.DetailList.length > 0">
						<div v-for="(item, index) in model.DetailList" :key="index">
							<div class="service_item ptb-24">
								<div class="service_img">
									<img-box class="productImg br-16 ofh" :img-url="item.ProductImage" />
								</div>
								<div class="ml-24 service_content">
									<div class="service_name">{{ item.Name }}</div>
									<div class="color-gray7 flex flex-s-c">
										<div>服务时长：{{ item.ProductServiceDuration }}分钟</div>
										<div class="addclock" v-if="model.State === 3 && isArtificer !== '1'" @click="addClock(item)">加钟</div>
										<div class="addclock"
											v-if="model.State === 3 && item.IsCanWriteOff === 1 && isArtificer === '1' && isOneClick === 1"
											@click="oneClick(item)">一键核销</div>
									</div>
									<div class="mt-36">
										<div><span class="service_unit fs-28">￥</span><span class="service_price">{{ item.Price ?
											item.Price.toFixed(2) : '' }}</span> <span>x{{ item.Amount }}</span></div>
										<div class="hexiao" v-if="model.State === 3 && isArtificer !== '1'" @click="GetRoomQrCode(item)">核销码
										</div>
									</div>
								</div>
							</div>
						</div>
					</div>
				</div>

				<!-- 加钟订单信息 -->
				<div class="bg-white mg-24 pd-24 br-16" v-if="BookHomeAddOrderList && BookHomeAddOrderList.length > 0">
					<div class="fs-28 fw-b">加钟项目</div>
					<div>
						<div v-for="(item, index) in BookHomeAddOrderList" :key="index">
							<div class="service_item ptb-24">
								<div class="service_img">
									<img-box class="productImg br-16 ofh" :img-url="item.ProductImage" />
								</div>
								<div class="ml-24 service_content">
									<div class="service_name">{{ item.Name }}</div>
									<div class="color-gray7 flex flex-s-c">
										<div>服务时长：{{ item.ProductServiceDuration }}分钟</div>
										<div class="addclock" v-if="item.State === 0 && isArtificer !== '1'" @click="goPay(item)">支付</div>
										<div v-if="item.State === 13 && isArtificer === '1' && isOneClick === 1">
											<div class="addclock" @click="oneClick(item)">一键核销</div>
										</div>
									</div>
									<div class="mt-36">
										<div><span class="service_unit fs-28">￥</span><span class="service_price">{{ item.Price ?
											item.Price.toFixed(2) : '' }}</span> <span>x{{ item.Amount }}</span></div>
										<div class="hexiao" v-if="item.State === 0 && isArtificer !== '1'" @click="cancle(item)">取消</div>
										<div class="hexiao" v-if="item.State === 13 && isArtificer !== '1'" @click="GetRoomQrCode(item)">核销码
										</div>
									</div>
								</div>
							</div>
						</div>
					</div>
				</div>

				<!-- 订单支付相关信息 -->
				<orderMsg :info="model"></orderMsg>

				<!-- 订单评价信息 -->
				<div v-if="isArtificer !== '1' && model.CommentModel">
					<div class="bg-white pd-24 mg-24 br-16">
						<div class="pb-24 mb-24 ordermsg_title fw-b fs-28">评价信息</div>
						<div class="flex flex-v-c">
							<div>
								<img-box class="face" :isBr50="isBr50" :img-url="model.CommentModel.Face" />
							</div>
							<div class="ml-24">
								<div class="color-black fw-b fs-28">{{ model.CommentModel.UserName }}</div>
								<div class="color-gray7">{{ model.CommentModel.AddTime }}</div>
							</div>
						</div>
						<div class="flex mt-24">
							<div>
								<img v-for="item in model.CommentModel.Star" src="@/assets/images/physio/satis.png" class="is-32 mr-12" />
								<img v-if="model.CommentModel.Star != 5" v-for="item in (5 - model.CommentModel.Star)"
									src="@/assets/images/physio/dissatis.png" class="is-32 mr-12" />
							</div>
						</div>
						<div class="fs-28 mt-24 text-show-line-2">{{ model.CommentModel.Content }}</div>
					</div>
				</div>

				<!-- 底部确认订单 -->
				<div class="fixed-bottom" v-if="model.State !== 5 && model.State !== 6">
					<div class="flex flex-fe-c ptb-20 plr-25 bg-white bottom-box" v-if="model.State === 3 && isArtificer === '1'">
						<button class="bg-physio-primary1 color-white  btn fs-26" @click.stop="writeOff(model)">核销</button>
					</div>
					<div class="flex flex-fe-c ptb-20 plr-25 bg-white bottom-box"
						v-else-if="model.State !== 3 && isArtificer !== '1'">
						<orderBtn :info="model" :switch30="switch30" @reset="reset" @refund="refund"></orderBtn>
					</div>
				</div>
				<!-- 核销码 -->
				<van-popup v-model="posterShow" class="posterDiv" :showConfirmButton="false" width="80%">
					<div class="poster_main pos-r bg-white bblr-32 bbrr-32 mb-70">
						<SvgIcon icon-class="close" class="fs-60 pos-a closecss z-out color-dark" @goPage="closeQrcode" />
						<div class="qrcode" id="qrcode" ref="qrcode"><img class="is-200" :src="qrcode" /></div>
						<div class="mt-40">核销码:{{ writeoffCode }}</div>
					</div>
				</van-popup>
				<!-- 加钟弹窗 -->
				<van-popup v-model="clockShow" class="pd-24 w-100">
					<div>
						<div class="service_items ptb-24">
							<div class="service_img">
								<img-box class="classImg br-16 ofh" :img-url="addClockMsg.ThumbnailUrl410" />
							</div>
							<div class="ml-24 service_content">
								<div class="service_name">{{ addClockMsg.ProductName }}</div>
								<div class="right-box-text color-gray7" v-if="addClockMsg.TagsList && addClockMsg.TagsList.length > 0">
									<span v-for="(items, index) in addClockMsg.TagsList" :key="index">{{ items.Name }}</span>
								</div>
								<div class="mt-36 flex flex-s-c">
									<div><span class="service_unit fs-28">￥</span><span class="service_price">{{ addClockMsg.V_GradePrice ?
										addClockMsg.V_GradePrice.toFixed(2) : '' }}</span></div>
									<van-stepper v-model="number" theme="round" button-size="24" integer disable-input />
									<!--<div class="flex-1 tar flex-fe-c" v-for="(iitem, index) in addClockMsg.ProductSkuList" :key="index">
											<span
												class="btn-minus flex-s-0 "
												:class="iitem.Amount <= 0 ? 'color-shadow' : ''"
												@click="changeAmount(iitem, iitem.Amount, iitem.Stock, -1, changeData.MinNum, activeUnitRatio, iitem.LimitBuy)"
											>-</span>
											<div class="btn-input-box">
												<input
													v-model="iitem.Amount"
													type="number"
													class="btn-input"
													@blur="changeAmount(iitem, item.Amount, iitem.Stock, 0, changeData.MinNum, activeUnitRatio, iitem.LimitBuy)"
												>
											</div>
											<span
												class="btn-plus flex-s-0"
												@click="changeAmount(iitem, iitem.Amount, iitem.Stock, 1, changeData.MinNum, activeUnitRatio, iitem.LimitBuy)"
											>+</span>
										</div>-->
								</div>
							</div>
						</div>
						<div class="placeorder color-white" @click="submitAddClock">确定加钟</div>
					</div>
				</van-popup>
				<!-- 退款原因 -->
				<van-dialog v-model="refundApply" title="请输入退款原因" show-cancel-button @confirm="OrderRefundApply"
					@cancel="cancelRefundApply">
					<van-field v-model="param.reason" type="textarea" class="fs-32 mt-15" placeholder="请输入退款原因~" rows="7"
						maxlength="50" />
				</van-dialog>
			</div>
		</div>
	</div>
</template>
<script>
import SvgIcon from 'components/SvgIcon'
import orderTop from 'components/physioOrder/orderTop.vue'
import orderMsg from 'components/physioOrder/orderMsg.vue'
import orderBtn from 'components/physioOrder/orderBtn.vue'
import imgBox from 'components/imgBox'
import { GetBookHomeOrderInfo, GetOrderWriteoffCodeList, GetArtificerProductPage, SubmitAddBookHomeOrder, GetCanArtificerWriteOff } from 'api/physio'
import { GetBusinessFunction } from 'api/businessSetting'
import jrQrcode from "jr-qrcode";
import { OrderRefundApply } from 'api/teaHouse'
import { SubmitWriteoff } from 'api/writeoff'
import { CancleOrder } from 'api/teaHouse'
export default ({
	components: {
		orderTop,
		orderMsg,
		imgBox,
		orderBtn,
		SvgIcon
	},
	props: {},
	data() {
		return {
			orderId: 0,
			model: {},
			refundApply: false,
			param: {}, //申请退款传参
			switch30: 0, //申请退款是否显示(0不显示 1显示)
			blank: false, // 是否为空数据
			posterShow: false, // 二维码弹窗显示
			qrcode: '', // 二维码图片地址
			ewm: '', // 点击开门码时存储所带数据生成二维码内容
			infos: {}, // 点击下载二维码存储所带数据(h5下载二维码图片名称)嵌套小程序只需长按图片保存所以
			remainder: '', //剩余支付时间
			paym: 0, //订单支付剩余分钟数
			pays: 0, //订单支付剩余秒数
			h: 0,	//服务剩余小时
			m: 0,	//服务剩余分钟
			s: 0, //服务剩余秒
			showPayTime: false, //是否显示订单支付倒计时
			showServiceTime: false, //是否显示服务倒计时
			writeoffCode: '', //核销码
			isArtificer: 0, //是否技师端 0否 1是
			technician: true,
			clockShow: false, //加钟弹窗显示
			addClockMsg: {}, //加钟信息
			changeData: [],
			activeUnitRatio: 1,
			cartRequestList: [],
			userCarListInput: {
				list: []
			}, // 购物车数据
			isOneClick: 0, //技师一键核销 1开启 0未开启
			userOrderInfo: [], //用户订单信息(判断订单id,取核销状态用)
			BookHomeAddOrderList: [], //加钟订单列表
			isBr50: true, //用来判断图片圆形
			number: 1, //加钟数量
		}
	},
	created() {
		this.orderId = this.$route.query.id  //订单id
		this.isArtificer = this.$route.query.isArtificer
		this.GetBusinessFunction()
		this.GetBookHomeOrderInfo()
		if (this.isArtificer === '1') {
			this.GetCanArtificerWriteOff()
		}

	},
	methods: {
		GetCanArtificerWriteOff() {
			GetCanArtificerWriteOff().then(res => {
				if (res) {
					this.isOneClick = res.Data
				}
			})
			GetOrderWriteoffCodeList({ orderId: this.orderId }).then(res => {
				if (res) {
					const a = res.Data.map(item => {
						return item.OrderDetailId
					})
					this.userOrderInfo = res.Data.filter((item, index) => {
						return a.indexOf(item.OrderDetailId) === index
					})
				}
			})
		},
		GetBookHomeOrderInfo() {
			GetBookHomeOrderInfo({ orderId: this.orderId }).then(res => {
				if (res) {
					this.BookHomeAddOrderList = []
					this.model = res.Data
					if (res.Data.State === 0) {
						this.countTime()
					} if (res.Data.State === 3) {
						this.countServiceTime()
					}
					if (res.Data.BookHomeAddOrderList && res.Data.BookHomeAddOrderList.length > 0) {
						res.Data.BookHomeAddOrderList.forEach(ele => {
							ele.DetailList[0].State = ele.OrderState
							this.BookHomeAddOrderList.push(ele.DetailList[0])
						})
					}
				}

			})
		},
		//获取开关权限
		GetBusinessFunction() {
			GetBusinessFunction(30).then(res => {
				if (res) {
					this.switch30 = res.Data[0].Value;
				}
			})
		},
		refund(item) {
			this.refundApply = true
			this.param.OrderId = item.OrderId
		},
		// 确认申请退款
		OrderRefundApply() {
			if (this.param.reason == '') {
				this.$toast('请输入退款原因')
				return
			}
			OrderRefundApply({
				orderId: this.param.OrderId,
				reason: this.param.reason,
				image: ''
			}).then(res => {
				if (res.Data) {
					// 获取列表
					this.reset()
				}
			})
		},
		// 取消申请退款
		cancelRefundApply() {
			this.param.reason = ''
			this.refundApply = false
		},
		reset() {
			this.GetBookHomeOrderInfo()
		},
		//核销
		writeOff() {
			this.$router.push('/physioWriteoff')
		},
		//一键核销
		oneClick(item) {
			GetOrderWriteoffCodeList({ orderId: item.OrderId, detailId: item.ID }).then(res => {
				if (res) {
					this.writeoffCode = res.Data[0].WriteoffCode
					SubmitWriteoff({ WriteoffCode: this.writeoffCode }).then(res => {
						if (res.Data) {
							this.GetBookHomeOrderInfo()
						}
					})
				}
			})

		},
		// 核销码
		GetRoomQrCode(item) {
			this.infos = item
			GetOrderWriteoffCodeList({ orderId: item.OrderId, detailId: item.ID }).then(res => {
				if (res.State == 0) {
					return
				}
				console.log(res.Data, "二维码")
				this.ewm = res.Data[0]
				this.writeoffCode = res.Data[0].WriteoffCode
				this.$nextTick(() => {
					let imgBase64 = jrQrcode.getQrBase64(this.writeoffCode, {//生成二维码
						padding: 10,   // 二维码四边空白（默认为10px）
						width: 200,  // 二维码图片宽度（默认为256px）
						height: 200,  // 二维码图片高度（默认为256px）
						correctLevel: QRErrorCorrectLevel.H,    // 二维码容错level（默认为高）
						reverse: false,        // 反色二维码，二维码颜色为上层容器的背景颜色
						background: "#ffffff",    // 二维码背景颜色（默认白色）
						foreground: "#000000"     // 二维码颜色（默认黑色）
					});  //options为配置对象，支持以下配置参数：
					this.qrcode = imgBase64
				})
				this.posterShow = true
			})
		},
		// 为了防止重复生成二维码，使用置空
		closeQrcode() {
			this.posterShow = false
			setTimeout(function () {
				this.qrcode = ''
			}, 150)
		},
		// 下载二维码
		saveImg() {
			let myCanvas = document.getElementById("qrcode").getElementsByTagName("img")
			let elink = document.createElement("a")
			elink.style.display = "none"
			document.body.appendChild(elink)
			elink.href = myCanvas[0].src
			elink.download = this.infos.RoomNo + this.infos.RoomName + "核销码"
			elink.click()
			document.body.removeChild(elink)
		},
		//订单支付倒计时
		countTime() {
			this.showPayTime = true
			//获取当前时间
			var date = new Date();
			var now = date.getTime();
			//设置截止时间
			var endDate = new Date(this.model.ValidTime);
			var end = endDate.getTime();
			//时间差
			var leftTime = end - now;
			//定义变量 d,h,m,s保存倒计时的时间
			if (leftTime >= 0) {
				var d = Math.floor(leftTime / 1000 / 60 / 60 / 24);
				this.h = Math.floor(leftTime / 1000 / 60 / 60 % 24);
				this.paym = Math.floor(leftTime / 1000 / 60 % 60);
				this.pays = Math.floor(leftTime / 1000 % 60);
			} else {
				this.showPayTime = false
			}
			if (this.paym > 0) {
				this.remainder = this.paym + '分钟' + this.pays + '秒'
			} else {
				this.remainder = this.pays + '秒'
			}
			//递归每秒调用countTime方法，显示动态时间效果
			setTimeout(this.countTime, 1000);
		},
		//服务结束倒计时
		countServiceTime() {
			this.showServiceTime = true
			//获取当前时间
			var date = new Date();
			var now = date.getTime();
			//设置截止时间
			var endDate = new Date(this.model.ServiceFinishTime);
			var end = endDate.getTime();
			//时间差
			var leftTime = end - now;
			//定义变量 d,h,m,s保存倒计时的时间
			if (leftTime >= 0) {
				var d = Math.floor(leftTime / 1000 / 60 / 60 / 24);
				this.h = Math.floor(leftTime / 1000 / 60 / 60 % 24);
				this.m = Math.floor(leftTime / 1000 / 60 % 60);
				this.s = Math.floor(leftTime / 1000 % 60);
			} else {
				this.showServiceTime = false
			}
			//递归每秒调用countTime方法，显示动态时间效果
			setTimeout(this.countServiceTime, 1000);
		},
		//加钟弹窗
		addClock(item) {
			this.clockShow = true
			GetArtificerProductPage({ artificerId: this.model.ArtificerId, ProductIds: item.ProductId }).then(res => {
				if (res.Data) {
					this.addClockMsg = res.Data.Data[0].ProductModel
				}
			})

		},
		changeAmount(item, num, stock, type, minNum, UnitRatio, LimitBuy) {
			item.Amount = num
			this.$utils.changeAmount(item, num, stock, type, minNum, UnitRatio, LimitBuy)
			const _obj = {}
			_obj.ProductId = item.ProductId
			_obj.Amount = item.Amount
			_obj.SkuId = item.ID
			_obj.Source = 0
			_obj.StoreId = item.StoreId
			_obj.V_GradePrice = item.V_GradePrice
			this.cartRequestList = this.cartRequestList.filter((ele) => {
				return ele.ProductId != item.ProductId
			});
			this.cartRequestList.push(_obj)
		},
		submitAddClock() {
			const list = {}
			const pskuList = this.addClockMsg.ProductSkuList[0]
			list.ProductId = pskuList.ProductId
			//list.Amount = pskuList.Amount	
			list.Amount = this.number
			list.SkuId = pskuList.ID
			list.Source = 0
			list.StoreId = pskuList.StoreId
			list.V_GradePrice = pskuList.V_GradePrice
			const requestData = {}
			this.userCarListInput.list.push(list)
			requestData.orderId = this.model.OrderId
			requestData.userCarListInput = this.userCarListInput
			if (list.Amount > 0) {
				SubmitAddBookHomeOrder(requestData).then(res => {
					if (res.Data) {
						window.location.href = this.$LocalDomain + '/m/product/PayOrder?id= ' + res.Data
							.OrderId + '&&singleflag=1&&isBookHomeOrder=1'
					}
				})
			} else {
				this.$toast("请选择加钟数量!")
			}
		},
		// 立即支付(加钟)
		goPay(item) {
			window.location.href = this.$LocalDomain + '/m/product/PayOrder?id=' + item.OrderId + '&&singleflag=1&&isBookHomeOrder=1'
		},
		//取消订单(加钟)
		cancle(item) {
			CancleOrder(item.OrderId).then(res => {
				if (res.Data) {
					// 获取列表
					this.GetBookHomeOrderInfo()
				}
			})
		},
	}

})
</script>
<style lang="scss" scoped>
.nav-top {
	width: 750px;
	height: 350px;
	background: #24C373;
}

.title {
	color: #fff;
	padding: 32px 0 20px 24px;
	display: flex;
	align-items: center;
	font-family: PingFangSC-Regular, PingFang SC;

	.status {
		font-size: 40px;
		font-weight: 500;
		margin-right: 16px;
	}
}

.service_item {
	display: flex;
	border-bottom: 2px solid #F2F3FC;
}

.service_item:last-child {
	border-bottom: none;
}

.service_name {
	font-size: 32px;
	color: $black2;
	margin-bottom: 12px;
}

.mt-36 {
	margin-top: 32px;
	display: flex;
	justify-content: space-between;
	align-items: center;
}

.service_unit {
	color: #EC612A;
}

.service_price {
	font-size: 36px;
	font-weight: bold;
	color: #EC612A;
	margin-right: 8px;
}

.service_img {
	width: 224px;
	height: 180px;
}

.productImg {
	width: 224px;
	height: 180px;
}

.service_content {
	width: calc(100% - 224px);
	display: flex;
	flex-direction: column;
	justify-content: space-between;
}

.hexiao {
	width: 128px;
	height: 48px;
	line-height: 48px;
	background: #FFFFFF;
	border-radius: 32px;
	border: 1px solid #666666;
	text-align: center;
}

.addclock {
	width: 128px;
	height: 48px;
	line-height: 48px;
	background: #4CA3F7;
	border-radius: 32px;
	text-align: center;
	color: #fff;
}

.endtime {
	width: 40px;
	height: 40px;
	background: #34267F;
	border-radius: 4px;
	font-size: 28px;
	color: #fff;
	text-align: center;
	margin: 0 8px;
}

.poster_main {
	text-align: center;
	padding: 62px 60px 62px;

	img {
		width: 450px;
		height: 450px;
	}

	p {
		font-size: 28px;
		color: #F54F1B;
		padding: 30px 0;
		font-weight: 500;
	}

	div {
		font-size: 28px;
		color: #333;
		font-weight: 400;
	}
}

.closecss {
	top: 20px;
	right: 16px;
	width: 50px;
	height: 50px;
}

.btn {
	width: 170px;
	height: 64px;
	line-height: 64px;
	border-radius: 32px;
	text-align: center;
	margin-right: 24px;
}

//加钟弹窗样式
.w-100 {
	width: 100%;
	border-radius: 24px;
}

.service_items {
	display: flex;
	justify-content: space-between;
}



.btn-minus {
	width: 40px;
	height: 40px;
	line-height: 40px;
	background: #F2F2F2;
	margin-right: 10px;
	border-radius: 50%;
	font-size: 40px;
	text-align: center;
}

.btn-plus {
	width: 40px;
	height: 40px;
	line-height: 40px;
	background: $physio-primary1;
	margin-left: 10px;
	border-radius: 50%;
	color: #fff;
	text-align: center;
	font-size: 40px;
}

.right-box-text span {
	background-color: #F2F3FC;
	padding: 4px 8px;
	border-radius: 4px;
	text-align: center;
	margin-right: 10px;
}

.classImg {
	width: 224px;
	height: 180px;
}

.placeorder {
	width: 224px;
	height: 72px;
	line-height: 72px;
	background: #24c373;
	border-radius: 36px;
	text-align: center;
	font-size: 28px;
	float: right;
	margin-top: 40px;
}

//加钟end

.face {
	width: 72px;
}

.ordermsg_title {
	border-bottom: 0.026667rem solid #F2F3FC;
}

.pb-220 {
	padding-bottom: 220px;
}

/deep/ .van-dialog__confirm {
	color: #24c373;
}

/deep/.van-stepper--round .van-stepper__minus {
	color: #333;
	border: 1px solid #f2f2f2;
	background: #f2f2f2;
}

/deep/.van-stepper--round .van-stepper__plus {
	color: #fff;
	background-color: #24c373;
}
</style>
